package com.danco.training.zaneuskaya.repository.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;


import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.danco.training.zaneuskaya.domain.Message;
import com.danco.training.zaneuskaya.domain.User;
import com.danco.training.zaneuskaya.repository.MessageDao;
/**
 * @author Zaneuskaya Aliaksandra
 *
 */
@Repository
public class MessageDaoImpl extends AbstractHibernateDao<Message, Integer> implements MessageDao {

	private static final String SENDER_MESSAGE = "sender";
	private static final String RECEIVER_MESSAGE = "receiver";
	private static final String MESSAGE_TIME = "messageTime";

	@Override
	public Message read(Integer PK) throws HibernateException {
		return super.read(Message.class, PK);
	}

	@Override
	public List<Message> readAll() throws HibernateException {
		
		return super.readAll(Message.class, MESSAGE_TIME);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Message> findMessagesBySender(User sender) throws HibernateException{
		List<Message> messages = new ArrayList<Message>();
		Criteria criteria = getSession().createCriteria(Message.class);
		criteria.add(Restrictions.eq(SENDER_MESSAGE, sender));
		criteria.addOrder(Order.desc(MESSAGE_TIME));
		messages =  criteria.list();
		return messages;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Message> findMessagesByReceiver(User receiver) throws HibernateException{
		List<Message> messages = new ArrayList<Message>();
		Criteria criteria = getSession().createCriteria(Message.class);
		criteria.add(Restrictions.eq(RECEIVER_MESSAGE, receiver));
		criteria.addOrder(Order.desc(MESSAGE_TIME));
		messages =  criteria.list();
		return messages;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Message> findMessagesByPeriod(Date from, Date to) throws HibernateException{
		List<Message> messages = new ArrayList<Message>();
		Criteria criteria = getSession().createCriteria(Message.class);
		criteria.add(Restrictions.between(MESSAGE_TIME, from, to));
		messages =  modifyCriteria(criteria,MESSAGE_TIME).list();
		return messages;
	}

	
	
}
